package com.jule.chat.network;

import com.google.protobuf.MessageLite;
import com.jule.chat.network.process.PingReq_50000;
import com.jule.chat.network.process.PongRes_50000;
import com.jule.chat.network.protocol.Request;
import com.jule.chat.network.protocol.Response;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xujian on 2017/5/16 0016.
 */
public class FunctionFactory {
    private final static Logger logger = LoggerFactory.getLogger(FunctionFactory.class);
    public static final int __function__id_50000 = 50000;//心跳


    private static final Map<Integer, Request> packetsPrototypesC = new HashMap<>();
    private static final Map<Integer, Response> packetsPrototypesS = new HashMap<>();

    public FunctionFactory() {
        packetsPrototypesC.put(__function__id_50000, new PingReq_50000(__function__id_50000));
        packetsPrototypesS.put(__function__id_50000 | 0xFF000000, new PongRes_50000(__function__id_50000 | 0xFF000000));
    }

    @SuppressWarnings("synthetic-access")
    private static class SingletonHolder {
        protected static final FunctionFactory instance = new FunctionFactory();
    }

    public static final FunctionFactory getInstance() {
        return SingletonHolder.instance;
    }

    /**
     * @param functionId
     * @param ctx
     * @return
     */
    public Request getRequest(final int functionId, final ChannelHandlerContext ctx) {
        Request request = packetsPrototypesC.get(functionId);
        if (request != null) {
            Request _request = request.clone();
            _request.setCtx(ctx);
            return _request;
        }
        logger.warn("收到未知数据包 function_id ->" + functionId);
        return null;
    }

    /**
     * @param functionId
     * @param messageLite
     * @return
     */
    public Response getResponse(final int functionId, MessageLite messageLite) {
        Response response = packetsPrototypesS.get(functionId);
        if (response != null) {
            Response _response1 = response.clone();
            _response1.setMessageLite(messageLite);
            return _response1;
        }
        return null;
    }
}
